package com.hyp.pay.UI.Home.activity;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.Toast;

import com.hyp.pay.R;
import com.hyp.pay.UI.Zxing.activity.TestScanActivity;
import com.hyp.pay.base.SimpleActivity;
import com.hyp.pay.camera.CameraHelper2;
import com.hyp.pay.camera.MaskSurfaceView2;
import com.hyp.pay.camera.OnCaptureCallback;
import com.hyp.pay.http.JsonUtil;
import com.hyp.pay.model.Face;
import com.hyp.pay.utils.SPUtil;
import com.hyp.pay.weight.ProgressDialog;
import com.hyp.pay.youtu.Youtu;

import org.json.JSONObject;

import java.io.File;

import butterknife.BindView;
import butterknife.OnClick;

import static com.hyp.pay.common.Config.APP_ID;
import static com.hyp.pay.common.Config.SECRET_ID;
import static com.hyp.pay.common.Config.SECRET_KEY;

public class FaceActivity extends SimpleActivity implements OnCaptureCallback {

    private static final int PHOTOS_SUCCESS =  200;
    private static final int PHOTOS_FAILURE =  500;

    //	拍照后得到的保存的文件路径
    private String mFilePath;
    private Handler mHandler;

    @BindView(R.id.surface_view)
    MaskSurfaceView2 mSurfaceView;
    @BindView(R.id.change_crame)
    ImageView mChangeCrame;
    @BindView(R.id.btn_capture)
    ImageView mBtnCapture;
    private String mCharge;
    private String mUserid;
    private ProgressDialog mDialog;
    private Bitmap theSelectedImage = null;

    @Override
    protected int getLayout() {
        return R.layout.activity_face;
    }


    @Override
    protected void initEventAndData() {


        mCharge = getIntent().getStringExtra("charge");
        mUserid = getIntent().getStringExtra("userid");
        mDialog=new ProgressDialog(mContext);

        mHandler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                switch (msg.what) {
                    case PHOTOS_SUCCESS:
//                        mDialog.dismiss();
                        CameraHelper2.getInstance().releaseCamera();
                        Toast.makeText(FaceActivity.this, "识别成功", Toast.LENGTH_SHORT).show();
                        Intent intent=new Intent(FaceActivity.this, TestScanActivity.class);
                        intent.putExtra("charge", mCharge);
                        intent.putExtra("userid", mUserid);
                        startActivity(intent);
                        finish();
                        break;
                    case PHOTOS_FAILURE:
                        Toast.makeText(FaceActivity.this, "识别失败，请重新拍照，尽量保持正脸正对屏幕", Toast.LENGTH_SHORT).show();
                        break;

                }
            }
        };

    }



    @OnClick({R.id.change_crame, R.id.btn_capture})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.change_crame:
                int cameraId = CameraHelper2.getInstance().getCameraId();
                if (cameraId == 0) {
                    CameraHelper2.getInstance().setCameraId(1);
                    CameraHelper2.getInstance().openCamera(mSurfaceView.surfaceView.getHolder(), 0, CameraHelper2.getInstance().width, CameraHelper2.getInstance().height, CameraHelper2.getInstance().screenWidth, CameraHelper2.getInstance().screenHeight);
                } else {
                    CameraHelper2.getInstance().setCameraId(0);
                    CameraHelper2.getInstance().openCamera(mSurfaceView.surfaceView.getHolder(), 0, CameraHelper2.getInstance().width, CameraHelper2.getInstance().height, CameraHelper2.getInstance().screenWidth, CameraHelper2.getInstance().screenHeight);
                }
                break;
            case R.id.btn_capture:
                CameraHelper2.getInstance().tackPicture(FaceActivity.this);
                break;
        }
    }

    @Override
    public void onCapture(boolean success, final String filePath) {
        this.mFilePath = filePath;
        String message = "拍照成功";
        if (!success) {
            message = "拍照失败";
            CameraHelper2.getInstance().startPreview();
            this.mSurfaceView.setVisibility(View.VISIBLE);
        } else {
            Toast.makeText(FaceActivity.this, "拍照成功", Toast.LENGTH_SHORT).show();
            CameraHelper2.getInstance().startPreview();
            theSelectedImage = getBitmap(filePath, 100, 100);
            new Thread(new Runnable() {
                @Override
                public void run() {
                    Looper.prepare();
//                    mDialog.show();
                    if (theSelectedImage != null) {
                        try {
                            Log.d("olj", "11111111111111111111");
                            Youtu faceYoutu = new Youtu(APP_ID, SECRET_ID, SECRET_KEY, Youtu.API_YOUTU_END_POINT);
                            JSONObject respose = faceYoutu.DetectFace(theSelectedImage, 1);
                            Log.d("olj", respose.toString());

                            Face faceData = JsonUtil.parseJson(respose.toString(), Face.class);
                            Log.d("olj", faceData.toString());
                            Log.d("olj", faceData.getErrormsg());
                            Log.d("olj", faceData.getErrorcode() + "");
                            if (faceData.getErrormsg().equals("OK") && faceData.getErrorcode() == 0) {

                                SPUtil.setSignFace(filePath);
                                sendMessage(PHOTOS_SUCCESS);
                                Toast.makeText(FaceActivity.this, "识别成功", Toast.LENGTH_SHORT).show();
                            } else {

                                sendMessage(PHOTOS_FAILURE);
                            }
                        } catch (Exception e) {
                            Log.i("olj",e.toString());
                            e.printStackTrace();
                        }
                    }
                }
            }).start();
            Looper.loop();

        }
    }


    private void sendMessage(int id ) {
        if (mHandler != null) {
            Message message = Message.obtain(mHandler, id);
            mHandler.sendMessage(message);
        }
    }


    private Bitmap getBitmap(String path, int maxWidth, int maxHeight) {
        //先解析图片边框的大小
        Bitmap bm = null;
        File file = new File(path);
        if (file.exists()) {
            BitmapFactory.Options ops = new BitmapFactory.Options();
            ops.inJustDecodeBounds = true;
            ops.inSampleSize = 1;
            BitmapFactory.decodeFile(path, ops);
            int oHeight = ops.outHeight;
            int oWidth = ops.outWidth;

            //控制压缩比
            int contentHeight = maxWidth;
            int contentWidth = maxHeight;
            if (((float) oHeight / contentHeight) < ((float) oWidth / contentWidth)) {
                ops.inSampleSize = (int) Math.ceil((float) oWidth / contentWidth);
            } else {
                ops.inSampleSize = (int) Math.ceil((float) oHeight / contentHeight);
            }
            ops.inJustDecodeBounds = false;
            bm = BitmapFactory.decodeFile(path, ops);

        }
        return bm;
    }
}
